<template>
  <div>
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 卡片视图 -->
    <el-card class="box-card">
      <el-row :gutter="20">
        <!-- 第1行第1列 -->
        <el-col :span="8">
          <!-- 搜索区 -->
          <el-input
            v-model="queryParams.query"
            placeholder="请输入内容"
            clearable
            @click="getUserslist"
          >
            <el-button
              slot="append"
              icon="el-icon-search"
              @click="getUserslist"
            ></el-button>
          </el-input>
        </el-col>
        <!-- 第1行第2列 -->
        <el-col :span="3">
          <!-- 添加用户按钮 -->
          <el-button type="primary" @click="dialogVisible = true"
            >添加用户</el-button
          >
        </el-col>
      </el-row>
      <!-- 内荣区 -->
      <el-table :data="Userlist" style="width: 100%">
        <!-- 索引列 -->
        <el-table-column type="index"></el-table-column>
        <el-table-column
          prop="username"
          label="姓名"
          width="180"
        ></el-table-column>
        <el-table-column
          prop="email"
          label="邮箱"
          width="180"
        ></el-table-column>
        <el-table-column
          prop="mobile"
          label="电话"
          width="180"
        ></el-table-column>
        <el-table-column
          prop="role_name"
          label="角色"
          width="180"
        ></el-table-column>
        <el-table-column prop="mg_state" label="状态" width="180">
          <template slot-scope="scope">
            <el-switch
              v-model="scope.row.mg_state"
              @change="changeState(scope.row)"
            >
            </el-switch>
          </template>
        </el-table-column>
        <!-- 操作列表 -->
        <el-table-column label="操作" width="180">
          <template slot-scope="scope">
            <el-button
              @click="showEditdialog(scope.row)"
              type="primary"
              icon="el-icon-edit"
              size="mini"
            ></el-button>
            <el-button
              type="danger"
              icon="el-icon-delete"
              size="mini"
              @click="deleteshow(scope.row)"
            ></el-button>
            <!-- 分配角色 -->
            <el-tooltip content="分配" placement="top">
              <el-button
                type="warning"
                icon="el-icon-setting"
                size="mini"
                @click="showRoleDiog(scope.row)"
              ></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryParams.pagenum"
        :page-sizes="[1, 2, 3, 4]"
        :page-size="queryParams.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>
    </el-card>

    <!-- 添加对话框-------------------------------------------------------------- -->
    <el-dialog
      v-dialogDrag
      title="提示"
      :visible.sync="dialogVisible"
      width="50%"
      @close="closeAddForm"
    >
      <!-- 主体内容 -->
      <el-form
        :model="addForm"
        :rules="addFormRules"
        ref="addFormRef"
        label-width="70px"
      >
        <el-form-item label="用户名" prop="username">
          <el-input v-model="addForm.username"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="addForm.password"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="addForm.email"></el-input>
        </el-form-item>
        <el-form-item label="手机" prop="mobile">
          <el-input v-model="addForm.mobile"></el-input>
        </el-form-item>
      </el-form>
      <!-- 尾部 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addUser">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 修改表单的 ----------------------------------------------- -->
    <el-dialog
      v-dialogDrag
      title="修改用户"
      :visible.sync="isEditShow"
      width="50%"
    >
      <!-- 主体内容 -->
      <el-form
        :model="editForm"
        :rules="editFormRules"
        ref="editFormRef"
        label-width="70px"
      >
        <el-form-item label="用户名" prop="username">
          <el-input v-model="editForm.username" disabled></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="editForm.email"></el-input>
        </el-form-item>
        <el-form-item label="手机" prop="mobile">
          <el-input v-model="editForm.mobile"></el-input>
        </el-form-item>
      </el-form>
      <!-- 尾部 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="isEditShow = false">取 消</el-button>
        <el-button type="primary" @click="editUser">确 定</el-button>
      </span>
    </el-dialog>

    <!--  分配角色对话框 -->
    <el-dialog
      title="分配角色"
      :visible.sync="isshowRoleDiog"
      width="50%"
      @close="closeRoles"
    >
      <div>用户名字：{{ curRole.username }}</div>
      <div>角色名字：{{ curRole.role_name }}</div>
      <div>
        分配角色：
        <el-select placeholder="请选择" v-model="selcetRolesID">
          <el-option
            v-for="item in roleList"
            :key="item.id"
            :label="item.roleName"
            :value="item.id"
          >
          </el-option>
        </el-select>
      </div>
      <!-- 按钮取 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="isshowRoleDiog = false">取 消</el-button>
        <el-button type="primary" @click="isokRole">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data () {
    return {
      // 修改对话框 显示隐藏开关
      isEditShow: false,
      // 修改表单数据对象
      editForm: {
        username: '',
        email: '',
        mobile: '',
        id: ''
      },
      // 修改用户 效验规则
      editFormRules: {
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          {
            type: 'email',
            message: '请输入正确的邮箱地址',
            trigger: ['blur', 'change']
          }
        ],
        mobile: [
          { required: true, message: '请输入亲爱的电话', trigger: 'blur' }
        ]
      },
      // 新增用户表单数据对象
      addForm: {
        username: '',
        password: '',
        email: '',
        mobile: ''
      },
      // 新增用户 效验对象
      addFormRules: {
        // 用户名效验规则
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          {
            min: 3,
            max: 10,
            message: '长度在 3 到 10 个字符',
            trigger: 'blur'
          }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          {
            min: 3,
            max: 10,
            message: '长度在 3 到 10 个字符',
            trigger: 'blur'
          }
        ],
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          {
            type: 'email',
            message: '请输入正确的邮箱地址',
            trigger: ['blur', 'change']
          }
        ],
        mobile: [
          { required: true, message: '请输入亲爱的电话', trigger: 'blur' }
        ]
      },
      // 设置 get 传入数据
      queryParams: {
        query: '', // 查询条件
        pagenum: 1, // 当前页码
        pagesize: 2 // 页容量
      },
      // 当前页面用户数组
      Userlist: [],
      // 页码、
      total: 0,
      dialogVisible: false,

      // 分配角色对话框 显示
      isshowRoleDiog: false,
      // 分配权限时 当前角色数据对象
      curRole: {},
      // 角色分配 使用的数组
      roleList: [],
      // 设置 分配对话框下拉选中角色的 id
      selcetRolesID: ''
    }
  },
  created () {
    // 调用请求 用户数据----
    this.getUserslist()
  },
  methods: {
    // 清楚对话框里的数据 保证在一次点击不会显示上一次的值
    closeRoles () {
      this.selcetRolesID = ''
      // 清空里面的里面的角色信息
      this.curRole = {}
    },
    // 分配对话框显示效果 ----------------
    async showRoleDiog (rowData) {
      // 显示对话框
      this.isshowRoleDiog = true
      // 把当前行保存到数组中方便视图中访问
      this.curRole = rowData
      // 向服务器请求 角色名字
      const { data: resData } = await this.$http.get('roles')
      // 如果失败
      if (resData.meta.status !== 200) { return this.$message.error(resData.meta.msg) }
      // 如果成功吧数据传入数组
      this.roleList = resData.data
    },
    // 对话框确认修改角色效果
    async isokRole () {
      const { data: resData } = await this.$http.put(
        `users/${this.curRole.id}/role`,
        {
          rid: this.selcetRolesID
        }
      )
      // 如果失败
      if (resData.meta.status !== 200) { return this.$message.error(resData.meta.msg) }
      // 如果成功
      this.$message.success(resData.meta.msg)
      // 关闭当前对话框
      this.isshowRoleDiog = false
      // 重新渲染
      this.getUserslist()
    },
    // 添加用户-----------------------
    addUser () {
      // 先效验表单结果 看是否通过
      this.$refs.addFormRef.validate(async (formData) => {
        // 里面 判断是否验证成功
        if (!formData) return
        // 发送post请求
        const { data: res } = await this.$http.post('users', this.addForm)
        // 如果失败
        if (res.meta.status != 201) {
          return this.$message.error('获取失败！！！~~')
        }
        // 如果成功 先关闭窗口，重新渲染数据
        this.dialogVisible = false
        this.$message.success('获取成功~~')
        this.getUserslist()
      })
    },
    // 对话框关闭事件函数---------------
    closeAddForm () {
      // 重置里面内容
      this.$refs.addFormRef.resetFields()
    },
    // 用户状态--------------------
    async changeState (UserData) {
      // 通过 ID 修改 状态
      const { data: resData } = await this.$http.put(
        `users/${UserData.id}/state/${UserData.mg_state}`
      )
      // 如果失败
      if (resData.meta.status !== 200) {
        UserData.mg_state = !UserData.mg_state
        return this.$message.error(resData.meta.msg)
      }

      // 如果成功
      this.$message.success(resData.meta.msg)
    },
    // 上传get---------------------
    async getUserslist () {
      // 上传get 事件
      const { data: res } = await this.$http.get('users', {
        params: this.queryParams
      })
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      // console.log(res.data.users)
      // 把数据存入 数组里面
      this.Userlist = res.data.users
      // 存入总页量
      this.total = res.data.total
    },
    //  切换页用量----------------------
    handleSizeChange (newSize) {
      // 修改 页面第几页
      this.queryParams.pagesize = newSize
      // 调入渲染
      this.getUserslist()
    },
    // 切换页-----------------
    handleCurrentChange (newIndex) {
      // 修改页容量
      this.queryParams.pagenum = newIndex
      this.getUserslist()
    },
    // 显示修改对话框 行数据-----------------
    showEditdialog (resData) {
      // console.log(resData)
      // 点击显示
      this.isEditShow = true
      // 渲染点击当前的内容
      this.editForm.username = resData.username
      this.editForm.email = resData.email
      this.editForm.mobile = resData.mobile
      this.editForm.id = resData.id
    },
    // 修改上传数据$-------------
    editUser () {
      // 表单效验
      this.$refs.editFormRef.validate(async (isok) => {
        if (!isok) return
        const { data: resData } = await this.$http.put(
          `users/${this.editForm.id}`,
          {
            email: this.editForm.email,
            mobile: this.editForm.mobile
          }
        )
        // 如果失败
        if (resData.meta.status !== 200) { return this.$message.error(resData.meta.msg) }
        // 如果成功 隐藏修改框
        this.isEditShow = false
        // 重新渲染
        this.getUserslist()
        this.$message.success('修改成功啦~~~~')
      })
    },
    // 删除----------------------
    async deleteshow (resData) {
      const { data: res } = await this.$http.delete(`users/${resData.id}`)
      if (res.meta.status !== 200) return this.$message.error('删除失败~~')
      this.$message.success('删除成功~~~')
      //  判断当钱页面的内容是否为1 如果为1 就页面先减一 在删除的时候就可以显示第三页的数据
      if (this.Userlist.length == 1) {
        // 页码减一
        this.queryParams.pagenum--
      }
      this.getUserslist()
    }
  }
}
</script>

<style lang="less" scoped>
</style>
